<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Cache;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Illuminate\Http\Request;
class WeixinController extends Controller
{
    /**
     * 获取用户信息
     */
    public function get_user_info(Request $request)
    {
        $user_info = Cache::has($request->input('code'));
        if(empty($user_info)){
            $app = app('wechat');
            $user = $app->oauth->user();
            $userService = $app->user;
            $user_info = $userService->get($user->getId());
            Cache::put($request->input('code'), json_encode($user_info), 5);
            return $this->response_object($user_info);
        }else{
            $user_info = Cache::get($request->input('code'));
            return $this->response_object(json_decode($user_info));
        }
    }


    /**
    * 统一下单
    */
    public function unifiedorder(Request $request)
    {
        $body           = $request->input('body');
        $detail         = $request->input('detail');
        $out_trade_no   = $request->input('out_trade_no');
        $total_fee      = $request->input('total_fee');
        $openid         = $request->input('openid');
        $notify_url     = 'http://weixin.51ffeng.cn/pay';
        $trade_type     = 'JSAPI';
        $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => 'iPad mini 16G 白色',
                'detail'           => 'iPad mini 16G 白色',
                'out_trade_no'     => uniqid(),
                'total_fee'        => 1,
                'notify_url'       => 'http://weixin.51ffeng.cn/pay', // 支付结果通知网址，如果不设置则会使用配置里的默认地址，我就没有在这里配，因为在.env内已经配置了。
                'openid'	   => 'oHZx6uNP6emvie1Ee5-HjklijklA',
                // ...
        ];
        //$attributes = compact('trade_type','body','detail','out_trade_no','total_fee','openid','notify_url');
        $wechat_config = config('wechat');
        $wechat_config['app_id'] = 'wx426b3015555a46be';
        $wechat_config['secret'] = '813490da6f1265e4901ffb80afaa36f';
        $app = new Application($wechat_config);
        $order = new Order($attributes);
        $result = $app->payment->prepare($order);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $js_config = $app->payment->configForPayment($result->prepay_id,false);
            return $this->response_object($js_config);
        }else{
            return $this->response_error(-1,$result->return_msg);
        }
    }

}
